import Vue from 'vue'
import VueRouter from 'vue-router'
// 默认会找里面的index.js或者index.vue
import login from '@/views/login'
import layout from '@/views/layout'
import dashboard from '@/views/dashboard'
import article from '@/views/article'
import { getToken } from '@/utils/storage'

import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  // 1级路由
  { name: 'login', path: '/login', component: login },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      { name: 'dashboard', path: 'dashboard', component: dashboard },
      { name: 'article', path: 'article', component: article }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 前置守卫
router.beforeEach((to, from, next) => {
  // 要么是登录页，要么是有token,都放行，其他都放行到登录页
  if (to.path === '/login' || getToken()) {
    next()
  } else {
    Message.warning('请先登录！')
    next('/login')
  }
})

export default router
